package com.ajview.core.config;

import com.ajview.common.core.domain.eneity.SysUser;
import com.ajview.common.utils.SecurityUtils;
import com.ajview.core.mybatisplus.interceptor.MybatisSqlLoggerInterceptor;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @author ZhangJunJie
 * @Date 2022-04-26
 * <p>
 * 概要： MyBatisplus 核心配置文件
 */
@Configuration
@Slf4j
@MapperScan("com.ajview.**.mapper")
public class MyBatisPlusConfig implements MetaObjectHandler {

    /**
     * 防止全表删除和更新操作
     * 如果全表删除或更新则抛出异常：MyBatisSystemException
     *
     * @return throws MyBatisSystemException
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        /*
         *  防止全表更新与删除
         * 针对 update 和 delete 语句
         */
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        /*
         * 乐观锁 实现
         * 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
         * 整数类型下 newVersion = oldVersion + 1
         * newVersion 会回写到 entity 中
         * 仅支持 updateById(id) 与 update(entity, wrapper) 方法
         * 在 update(entity, wrapper) 方法下, wrapper 不能复用!!!
         *
         * @return
         */
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        /*
         * 新的分页插件,一缓和二缓遵循mybatis的规则
         */
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.H2);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);

        return interceptor;
    }


    /**
     * MyBatis拦截器打印不带问号的完整sql语句
     * 只在开发环境运行
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(value = "spring.profiles.active", havingValue = "dev")
    public MybatisSqlLoggerInterceptor mybatisSqlLoggerInterceptor() {
        return new MybatisSqlLoggerInterceptor();
    }

    /**
     * 自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        if (SecurityUtils.AUTHENTICATION_NAME.equals(SecurityUtils.getAuthentication().getName())) {
            this.strictInsertFill(metaObject, "updateBy", String.class, "未登录");
            this.strictInsertFill(metaObject, "createBy", String.class, "未登录");

            this.strictInsertFill(metaObject, "updateById", Long.class, null);
            this.strictInsertFill(metaObject, "createById", Long.class, null);
        } else {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            this.strictInsertFill(metaObject, "updateBy", String.class, sysUser.getUserName());
            this.strictInsertFill(metaObject, "createBy", String.class, sysUser.getUserName());

            this.strictInsertFill(metaObject, "updateById", Long.class, sysUser.getUserId());
            this.strictInsertFill(metaObject, "createById", Long.class, sysUser.getUserId());

        }

        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());


        this.strictInsertFill(metaObject, "delFlag", String.class, "0");
    }

    /**
     * 自动填充更新
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        if (SecurityUtils.AUTHENTICATION_NAME.equals(SecurityUtils.getAuthentication().getName())) {
            this.strictInsertFill(metaObject, "updateBy", String.class, "未登录");
            this.strictInsertFill(metaObject, "updateById", Long.class, 0L);
        } else {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            this.strictInsertFill(metaObject, "updateBy", String.class, sysUser.getUserName());
            this.strictInsertFill(metaObject, "updateById", Long.class, sysUser.getUserId());
        }
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

}
